#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2020/4/19  19:33
# @Author: 余浪人
# @email: yulangren520@gmail.com
import os, uuid
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, QueryDict
from django.utils.decorators import method_decorator
from django.views import View
from public import update_data, cleaned_data, verify_obj
from system import system_path
from system.forms import *
from .models import *


class ChapterGet(View):

    @method_decorator(login_required)
    def get(self, request):
        uuid = request.GET.get('uuid')
        try:
            objList = ChapterModel.objects.order_by('-create_time').filter(novel=uuid)
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '获取数据异常', 'error': str(e)})
        dataList = [{
            'chapter': obj.title,
            'uuid': obj.uuid,
            'is_pay': obj.is_pay,
            'author': obj.novel.novel_author
        } for obj in objList]
        return JsonResponse({'code': 0, 'data_list': dataList})

    @method_decorator(login_required)
    def delete(self, request):
        uuid = QueryDict(request.body).get('uuid')
        if not uuid: return JsonResponse({'code': 1, 'msg': '移出章节错误!', 'error': '未获取到关键参数'})
        try:
            ChapterModel.objects.filter(uuid=uuid).delete()
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '移出章节异常!', 'error': str(e)})
        return JsonResponse({'code': 0, 'msg': '移出章节成功!'})


class LinkEditView(View):

    @method_decorator(login_required)
    def get(self, request):
        uuid = request.GET.get('uuid')
        if not uuid: return JsonResponse({'code': 1, 'msg': '未检测到有效参数'})
        obj = Blogroll_Model.objects.filter(uuid=uuid).first()
        if not obj: return JsonResponse({'code': 1, 'msg': '未检测到有效数据'})
        return JsonResponse({'code': 0, 'msg': 'success', 'data': dict(obj)})

    @method_decorator(login_required)
    def post(self, request):
        uuid = request.POST.get('uuid')
        return update_data(request, LinkForm, Blogroll_Model, uuid)


class AdEditView(View):

    @method_decorator(login_required)
    def get(self, request):
        uuid = request.GET.get('uuid')
        if not uuid: return JsonResponse({'code': 1, 'msg': '未检测到有效参数'})
        obj = Ad_Model.objects.filter(uuid=uuid).first()
        if not obj: return JsonResponse({'code': 1, 'msg': '未检测到有效数据'})
        return JsonResponse({'code': 0, 'msg': 'success', 'data': dict(obj)})

    @method_decorator(login_required)
    def post(self, request):
        uuid = request.POST.get('uuid')
        return update_data(request, AdForm, Ad_Model, uuid)


class UploadFile(View):
    @method_decorator(login_required)
    def post(self, request):
        obj = request.FILES.get('file')
        name = f"{''.join(str(uuid.uuid4()).split('-')[:2]).replace('-', '')}.{obj.name.split('.')[1]}".replace(" ", "")
        try:
            save = Save_Model.objects.first()
            path = os.path.join(save.save_path.replace('/', ''), datetime.now().strftime('%Y%m%d'))
        except:
            return JsonResponse({'code': 4, 'url': '', 'msg': '调取上传类别错误！'})
        if save.save_classification == 1:
            try:
                abspath_dir = os.path.join(system_path, 'static', path).replace('\\', '/')
                if not os.path.exists(abspath_dir): os.makedirs(abspath_dir)
                fp = open(os.path.join(abspath_dir, name), 'wb')
                for line in obj.chunks():
                    fp.write(line)
                fp.close()
                url = os.path.join(path, name)
            except Exception as e:
                return JsonResponse({'code': 4, 'url': '', 'msg': str(e)})
        else:
            url = ''
            q = Auth(save.access_key, save.secret_key)
            _path = save.save_path[1:] if save.save_path[0] == '/' else save.save_path
            _path = _path if _path[-1] == '/' else _path + '/'
            fileName_ = os.path.join(_path, fileName)  # todo
            token = q.upload_token(save_obj.bucket_name, fileName_, 3600)
            ret, info = put_data(token, fileName_, file_data)
            assert ret['key'] == fileName_
            base = save_obj.bucket_domain if save_obj.bucket_domain[-1] == '/' else save_obj.bucket_domain + '/'
            return base + fileName_
        return JsonResponse({'code': 0, 'url': url, 'msg': 'success'})


class ChapterIsPay(View):
    @method_decorator(login_required)
    def get(self, request):
        uuid = request.GET.get('uuid')
        if not uuid.strip(): return JsonResponse({"code": 1, 'msg': '参数有误', 'error': '关键参数获取失败'})
        try:
            is_pay = True if request.GET.get('is_pay') == 'true' else False
            obj = ChapterModel.objects.filter(uuid=uuid)
            if obj.count(): obj.update(**{'is_pay': is_pay})
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '处理异常', 'error': f'[info] {e}'})
        return JsonResponse({'code': 0})


class Navigation(View):
    @method_decorator(login_required)
    def get(self, request):
        uuid = request.GET.get('uuid')
        if not uuid.strip(): return JsonResponse({"code": 1, 'msg': '参数有误', 'error': '关键参数获取失败'})
        try:
            # is_pay = True if request.GET.get('column_display') == 'true' else False
            obj = NavigationModel.objects.filter(uuid=uuid)
            if obj.count(): obj.update(**{'column_display': not obj.first().column_display})
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '处理异常', 'error': f'[info] {e}'})
        return JsonResponse({'code': 0})

    @method_decorator(login_required)
    def post(self, request):
        uuid = request.POST.get('uuid')
        if not uuid.strip(): return JsonResponse({"code": 1, 'msg': '参数有误', 'error': '关键参数获取失败'})
        try:
            # is_pay = True if request.POST.get('column_index_show') == 'true' else False
            obj = NavigationModel.objects.filter(uuid=uuid)
            if obj.count(): obj.update(**{'column_index_show': not obj.first().column_index_show})
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '处理异常', 'error': f'[info] {e}'})
        return JsonResponse({'code': 0})


class NovelEdit(View):
    @method_decorator(login_required)
    def get(self, request):
        uuid = request.GET.get('uuid')
        try:
            obj = NovelModel.objects.filter(uuid=uuid).first()
            data = dict(obj)
            data['categories'] = dict(data['categories'])
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '获取数据异常', 'error': str(e)})
        return JsonResponse({'code': 0, 'data': data})

    @method_decorator(login_required)
    def post(self, request):
        uuid = request.POST.get('uuid')
        obj = NovelModel.objects.filter(uuid=uuid)
        data = cleaned_data(dict(request.POST), obj.first())
        try:
            data['novel_state'] = True if data['novel_state'] == 'true' else False
            if verify_obj(obj.first()): obj.update(**data)
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '更新数据异常', 'error': str(e)})
        return JsonResponse({'code': 0, 'msg': '更新数据成功'})


class NovelShow(View):
    @method_decorator(login_required)
    def get(self, request):
        uuid = request.GET.get('uuid')
        obj = NovelModel.objects.filter(uuid=uuid)
        try:
            obj.update(novel_is_recommend= not obj.first().novel_is_recommend)
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '切换异常', 'error': str(e)})
        return JsonResponse({'code': 0})

    @method_decorator(login_required)
    def post(self, request):
        uuid = request.POST.get('uuid')
        obj = NovelModel.objects.filter(uuid=uuid)
        try:
            obj.update(novel_is_focus=not obj.first().novel_is_focus)
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '切换异常', 'error': str(e)})
        return JsonResponse({'code': 0})
